<template>
  <div style="height: 100%;">
    <div class="verify_top">
      <div class="areatitle left">
        <div class="textpart">
          <img :src="titlepng"/>
          <h4>识别区域</h4>
        </div>
      </div>
      <div class="verifybor">
        <div class="facearea">
          <div class="faceimg">
            <img :src="faceDetectUrl? faceDetectUrl: nonepng"/>
          </div>
          <div class="upload_btn">
            <a href="javascript:;" class="upbtn">
              上传头像
            </a>
            <a href="javascript:;" class="file-button">
              <input type="file" class="hidden_btn" accept=“image/*” @change="inputChange">
            </a>
          </div>
        </div>
        <div class="animate fadeOut faceLoading" v-if="!faceDetectUrl&&faceLoading">
          <div id="preloader_1">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <p>加载中...</p>
          </div>
        </div>
        <div class="info animated fadeIn" v-if="faceDetectUrl">
          <div class="person_num">
            <span v-for="(item, index) in faceNum" v-bind:key="item.id" :class="{active:activeIndex === index}">
              <i class="fa fa-user" @click="showPerson(index)"></i>
              <p>识别{{index+1}}</p>
            </span>
          </div>
          <div class="verifyface">
            <div class="compared">
              <div class="getimg">
                <!--<img :src="similarFaceUrl" v-show="similarFaceUrl">-->
                <img :src="similarFaceUrl? similarFaceUrl: nonepng"/>
              </div>
            <div class="ratio">
              <!--<h4 :class="{error: compareError}">{{faceInfo}}</h4>-->
              <!--<h4>匹配度<span>99%</span></h4>-->
              <!--<h4 v-if="errorMes" class="error">无搜索结果</h4>-->
              <h4 :class="{error:errorMes}">
                <div v-if="!withVerity">{{faceInfo}}</div>
                <div v-if="withVerity">
                  相似度:<span>{{faceInfo}}</span>
                </div>
              </h4>
            </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="verify_bottom">
      <div class="areatitle left">
        <div class="textpart">
          <img :src="titlepng"/>
          <h4>特征</h4>
        </div>
      </div>
      <div class="verifybor verifybor2">
        <div class="featurelist">
          <!--<div class="facelist" v-for="item in facelist" v-bind:key="item.id">-->
            <div class="item">
              <div>年龄：<span>{{feartureItem.age}}</span></div>
              <div>性别：<span>{{feartureItem.genderMaleScore | genderFilter}}</span></div>
              <div>人种：<span>{{feartureItem.race}}</span></div>
              <div>眼镜：<span>{{feartureItem.eyeGlassScore | hasFilter}}</span></div>
              <div>胡须：<span>{{feartureItem.beardScore | hasFilter}}</span></div>
            </div>
            <div class="item">
              <div>张嘴：<span>{{feartureItem.mouthOpenScore | hasFilter}}</span></div>
              <div>睁眼：<span>{{feartureItem.eyeOpenScore | hasFilter}}</span></div>
              <div>眯眼：<span>{{feartureItem.squintScore | hasFilter}}</span></div>
              <div>化妆：<span>{{feartureItem.maskScore | hasFilter}}</span></div>
              <div>太阳镜：<span>{{feartureItem.sunGlassScore | hasFilter}}</span></div>
            </div>
            <div class="item">
              <div>镇静指数：<span>{{feartureItem.calmScore}}</span></div>
              <div>快乐指数：<span>{{feartureItem.happyScore}}</span></div>
              <div>生气指数：<span>{{feartureItem.angryScore}}</span></div>
              <div>恐惧指数：<span>{{feartureItem.scaredScore}}</span></div>
              <div>微笑指数：<span>{{feartureItem.smileScore}}</span></div>
            </div>
            <div class="item">
              <div>惊讶指数：<span>{{feartureItem.surprisedScore}}</span></div>
              <div>困惑指数：<span>{{feartureItem.confusedScore}}</span></div>
              <div>伤心指数：<span>{{feartureItem.sadScore}}</span></div>
              <div>厌恶指数：<span>{{feartureItem.disgustScore}}</span></div>
              <div>魅力指数：<span>{{feartureItem.attrActive}}</span></div>
            </div>
            <div class="item">
              <div>惊叫指数：<span>{{feartureItem.screamScore}}</span></div>
            </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        titlepng: require('@/assets/img/title-bg.png'),
        nonepng: require('../assets/img/none.png'),
        imgFile: {},
        faceDetectUrl: '',
        faceInfo: '',
        similarFaceUrl: '',
        facelist: [],
        faceNum: 0,
        errorMes: false,
        compareError: false,
        imageUrl: '',
        feartureItem: {},
        activeIndex: 0,
        withVerity: Boolean,
        faceLoading: false
      }
    },
    filters: {
      genderFilter: function (val) {
        let gender = typeof (val) === 'undefined' ? '' : val >= 50 ? '男' : '女'
        return gender
      },
      hasFilter: function (val) {
        let hasOrnot = typeof (val) === 'undefined' ? '' : val >= 50 ? '有' : '无'
        return hasOrnot
      }
    },
    methods: {
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      inputChange: function (e) {
        const file = event.target.files[0]
        const imgMasSize = 1024 * 1024 * 10

        // 检查文件类型
        if (['jpeg', 'png', 'gif', 'jpg'].indexOf(file.type.split('/')[1]) < 0) {
          // 自定义报错方式
          // Toast.error("文件类型仅支持 jpeg/png/gif！", 2000, undefined, false);
          alert('请上传图片文件')
          return
        }
        // 文件大小限制
        if (file.size > imgMasSize) {
          alert('文件大小请小于10M')
          return
        }
        this.transformFileToDataUrl(file)
        this.faceLoading = true
      },
      transformFileToDataUrl: function (file) {
        // const imgCompassMaxSize = 200 * 1024

        // 存储文件相关信息
        this.imgFile.type = file.type || 'image/jpeg'
        this.imgFile.size = file.size
        this.imgFile.name = file.name
        this.imgFile.lastModifiedDate = file.lastModifiedDate

        // 封装好的函数
        const reader = new FileReader()
        var vm = this

        // file转dataUrl是个异步函数，要将代码写在回调里
        reader.onload = function (e) {
          const result = e.target.result
          vm.compress(result, vm.processData, false)
          // if (result.length < imgCompassMaxSize) {
          //   this.compress(result, this.processData, false)
          // } else {
          //   this.compress(result, this.processData)
          // }
        }
        reader.readAsDataURL(file)
      },
      compress: function (dataURL, callback, shouldCompress = true) {
        const img = new window.Image()
        var vm = this
        img.src = dataURL
        img.onload = function () {
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          canvas.width = img.width
          canvas.height = img.height
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
          let compressedDataUrl
          if (shouldCompress) {
            compressedDataUrl = canvas.toDataURL(vm.imgFile.type, 0.2)
          } else {
            compressedDataUrl = canvas.toDataURL(vm.imgFile.type, 1)
          }
          callback(compressedDataUrl)
        }
      },
      processData: function (dataUrl) {
        const binaryString = window.atob(dataUrl.split(',')[1])
        const arrayBuffer = new ArrayBuffer(binaryString.length)
        const intArray = new Uint8Array(arrayBuffer)
        const imgFile = this.imgFile

        for (let i = 0, j = binaryString.length; i < j; i++) {
          intArray[i] = binaryString.charCodeAt(i)
        }
        const data = [intArray]
        let blob
        try {
          blob = new Blob(data, {type: imgFile.type})
        } catch (error) {
          window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder
          if (error.name === 'TypeError' && window.BlobBuilder) {
            const builder = new window.BlobBuilder()
            builder.append(arrayBuffer)
            blob = builder.getBlob(imgFile.type)
          } else {
            this.faceLoading = false
            // Toast.error("版本过低，不支持上传图片", 2000, undefined, false);
            throw new Error('版本过低，不支持上传图片')
          }
        }

        // blob 转file
        const fileOfBlob = new File([blob], imgFile.name)
        const formData = new FormData()

        // type
        formData.append('type', imgFile.type)
        // size
        formData.append('size', fileOfBlob.size)
        // name
        formData.append('name', imgFile.name)
        // lastModifiedDate
        formData.append('lastModifiedDate', imgFile.lastModifiedDate)
        // append 文件
        formData.append('file', fileOfBlob)
        this.uploadImg(formData)
      },
      uploadImg: function (formData) {
        var vm = this
        const xhr = new XMLHttpRequest()

        // 进度监听
        xhr.upload.addEventListener('progress', (e) => {
          console.log(e.loaded / e.total)
        }, false)
        // 加载监听
        // xhr.addEventListener('load', ()=>{console.log("加载中");}, false);
        // 错误监听
        xhr.addEventListener('error', () => {
          this.faceLoading = false
          alert('上传失败')
        }, false)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            const result = JSON.parse(xhr.responseText)
            if (xhr.status === 200) {
              // 上传成功
              vm.detectFace(result.data)
            } else {
              this.faceLoading = false
              alert('上传失败')
            }
          }
        }
        xhr.open('POST', this.FSA + '/file/upload', true)
        xhr.send(formData)
      },
      detectFace: function (fullFileName) {
        var vm = this
        this.faceDetectUrl = this.FSA + '/face/detectImg?fullFileName=' + fullFileName
        this.axios.get(this.FSA + '/face/getFaceInfo', {
          params: {
            fullFileName: fullFileName
          }
        }).then(function (response) {
//          this.faceLoading = false
          var result = response.data.data
          console.log(response)
          if (response.data.code === 0) {
            vm.faceNum = result.faceAttrStr ? result.faceAttrStr.length : 0
            if (result.faceAttrStr) {
              vm.faceNum = result.faceAttrStr.length
              vm.facelist = result.faceAttrStr
              vm.feartureItem = vm.facelist[0]
            } else {
              vm.errorMes = true
            }
            console.log(vm.facelist)
          } else {
            setTimeout(() => {
              vm.errorMes = true
            }, 1000)
          }
        }).catch(function (error) {
          console.log(error)
        })
        this.axios.get(this.FSA + '/face/verify', {
          params: {
            fullFileName: fullFileName
          }
        }).then(function (response) {
          console.log(response)
          var data = response.data
          if (data.code === 0) {
            data = data.data
            vm.compareError = false
            if (data) {
              console.log(data.similarity)
              vm.faceInfo = (data.similarity * 100).toFixed(2) + '%'
              vm.withVerity = true
            }
            vm.similarFaceUrl = vm.FSA + '/file/downloadImg?fileId=' + data.mostSimilarFaceId
          } else {
            vm.faceInfo = '图像库中无记录'
            vm.compareError = true
            vm.withVerity = false
            vm.similarFaceUrl = vm.nonepng
          }
        }).catch(function (error) {
          console.log(error)
        })
        this.faceLoading = false
      },
      showPerson: function (index) {
        this.activeIndex = index
        this.feartureItem = this.facelist[index]
      }
    },
    mounted() {
    }
  }
</script>
